package sggJuc.future;

import java.util.Random;
import java.util.concurrent.*;

/**
 * CompletableFuture减少阻塞和轮询
 *
 * @author xizheng
 * @date 2023-08-08 10:15:57
**/
public class CompletableFutureUseDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        future1();
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        try {
            CompletableFuture<Integer> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
                int count =  ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
//                if(true){
//                    int i=10/0;
//                }
                return  count;
            },executorService).whenComplete((v,e) ->{
                if(e == null){
                    System.out.println("更新结果" + v);
                }
            }).exceptionally(e->{
                e.printStackTrace();
                return null;
            });
        } finally {
            executorService.shutdown();
        }
        System.out.println("主线程执行");
    }

    public static void future1() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "----come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("----1秒钟后出结果: " + result);
            return result;
        });

        System.out.println(Thread.currentThread().getName()+"线程先去忙其它任务");

        System.out.println(completableFuture.get());
    }

}
